<!--
 * @Author       : xh
 * @Date         : 2022-10-20 16:21:55
 * @LastEditors  : xh
 * @FileName     :
-->
<template>
  <div ref="dragTable" class="dragbar">
    <el-table style="width: 100%" v-bind="$attrs">
      <el-table-column v-if="props.sortPosition === 'left'" prop="drag" label="" width="40">
        <div class="dragblock">
          <el-icon><Rank /></el-icon>
        </div>
      </el-table-column>
      <slot></slot>
      <el-table-column v-if="props.sortPosition === 'right'" prop="drag" label="" width="40">
        <div class="dragblock">
          <el-icon><Rank /></el-icon>
        </div>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import Sortable from 'sortablejs'
import { onMounted, nextTick, ref, useAttrs, defineEmits, defineProps } from 'vue'
const attrs = useAttrs()
const dragTable = ref()
const tableData = ref([])
onMounted(() => {
  // console.log('$attrs', attrs)
  tableData.value = attrs.data
  nextTick(() => {
    initDropTable()
  })
})
const props = defineProps({
  sortPosition: {
    default: 'right',
    type: String
  }
})
const emits = defineEmits(['sortSuccess'])

const initDropTable = () => {
  const el = dragTable.value.querySelector('.el-table__body tbody')
  // console.log('dragTable', el)
  Sortable.create(el, {
    handle: '.dragblock', // 设置指定列作为拖拽
    onEnd(evt) {
      const { newIndex, oldIndex } = evt
      console.log(newIndex)
      console.log(oldIndex)
      const arr = [...tableData.value]
      const currRow = arr?.splice(oldIndex, 1)[0]
      arr?.splice(newIndex, 0, currRow)

      tableData.value = arr
      console.log('tableData', tableData.value)
      sortIndex()
    }
  })
}

const sortIndex = () => {
  const array = []
  tableData.value.forEach((e, i) => {
    const obj = {
      id: e.name,
      index: i + 1
    }
    array.push(obj)
  })
  console.log('array', array)
  emits('sortSuccess', array)
}
</script>

<style lang="scss" scoped>
.dragblock {
  cursor: pointer;
}
</style>
